/**
 * 
 */
package com.nxin.file.manage.generate.strategy;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import com.nxin.file.manage.utils.Constants;
import com.nxin.file.manage.utils.User;

/**
 * @author qijin
 *
 */
public class CsvGenerateStrategy implements FileGenerateStrategy {

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.nxin.file.manage.generate.strategy.FileGenerateStrategy#generate()
	 */
	@SuppressWarnings("unchecked")
	public void generate(Object data, File file) throws FileNotFoundException {
		FileOutputStream out = new FileOutputStream(file);
		try {
			// 输出标题头
			// 注意列之间用","间隔,写完一行需要回车换行"\r\n"
			String title = "序号,姓名,年龄,性别"+Constants.TEXT_DEFAULT_LINE_FEEDS;
			out.write(title.getBytes(Constants.TEXT_DEFAULT_CHARTSET));
			
			List<User> userList = (List<User>) data;
			StringBuilder sb = new StringBuilder();
			for (int i = 0; i < userList.size(); i++) {
				User user = userList.get(i);
				sb.delete( 0, sb.length());
				// 注意列之间用","间隔,写完一行需要回车换行"\r\n"
				sb.append(user.getNo()).append(",").append(user.getName()).append(",").append(user.getAge()).append(",").append(user.getGender()).append(Constants.TEXT_DEFAULT_LINE_FEEDS);
				out.write(sb.toString().getBytes(Constants.TEXT_DEFAULT_CHARTSET));
			}
			out.flush();
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		} finally {
			try {
				if (out != null) {
					out.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

}
